import java.util.*;

/**
 * @author LKQ
 * @date 2022/5/10 15:47
 * @description 二分查找，升序数组中查找target的开始位置和结束位置， 使用蓝红区间二分法模板
 */
public class Solution3 {
    public static void main(String[] args) {

    }
    public int[] searchRange(int[] nums, int target) {
        int n = nums.length;
        int start = binarySearch(nums, target);
        int end = binarySearch2(nums, target);
        if (start == n || end == -1 || start > end) {
            // 如果找到边界或者 开始位置 > 结束位置
            return new int[] {-1, -1};
        }
        return new int[] {start, end};
    }

    /**
     * 返回第一个大于等于target的下标
     * @param nums nums
     * @param target target
     * @return index
     */
    public int binarySearch(int[] nums, int target) {
        int l = -1, r = nums.length;
        while (l + 1 != r) {
            int mid = (l + r) / 2;
            if (nums[mid] < target) {
                l = mid;
            }else {
                r = mid;
            }
        }
        return r;
    }
    /**
     * 返回最后一个小于等于target的下标
     * @param nums nums
     * @param target target
     * @return index
     */
    public int binarySearch2(int[] nums, int target) {
        int l = -1, r = nums.length;
        while (l + 1 != r) {
            int mid = (l + r) / 2;
            if (nums[mid] <= target) {
                l = mid;
            }else {
                r = mid;
            }
        }
        return l;
    }
}
